package com.mjlf.restclient.template;

import com.mjlf.restclient.client.Template;
import com.mjlf.restclient.entity.RestParams;
import okhttp3.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

/**
 * @ClassName Template
 * @Author mjlft
 * @Date 2020/2/18 10:30
 * @Version 1.0
 * @Description TODO
 */
@Component
@ConditionalOnClass(OkHttpClient.class)
public class RestTemplate implements Template {
    private OkHttpClient client = new OkHttpClient();
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    @Override
    public String get(RestParams params) throws Exception {
        Request.Builder builder = new Request.Builder()
                .url(params.getUrl());
        if (params.getHeaders() != null) {
            params.getHeaders().names().forEach(name -> {
                builder.addHeader(name, params.getHeaders().get(name));
            });
        }

        try (Response response = client.newCall(builder.build()).execute()) {
            return response.body().string();
        }
    }

    @Override
    public String post(RestParams params) throws Exception {
        RequestBody body = RequestBody.create(params.getParams(), JSON);
        Request.Builder builder = new Request.Builder()
                .url(params.getUrl())
                .post(body);
        if (params.getHeaders() != null) {
            params.getHeaders().names().forEach(name -> {
                builder.addHeader(name, params.getHeaders().get(name));
            });
        }
        Request request = builder.build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }
}
